//
//  StatusPictureView.swift
//  仿一个新浪微博
//
//  Created by 孙家林 on 15/9/23.
//  Copyright © 2015年 sunjialin. All rights reserved.
//

import UIKit

import SDWebImage

/// 可重用 cell 标示符
private let statusPictureViewCellID = "statusPictureViewCellID"

class StatusPictureView: UICollectionView {
    
    var status: Status? {
        
        didSet {
            
            sizeToFit()
            
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        
        return calcViewSize()
    }
    
    //计算视图大小
    private func calcViewSize() -> CGSize {
        
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        
        //设置每一行最多显示的图片
        let rowCount = 3
        
        pictureLayout.itemSize = itemSize
        
        //1、根据图片数量计算视图大小
        let count = status?.pictureURLs?.count ?? 0
        
        if count == 0 {
            
            return CGSizeZero
        }
        
        if count == 1 {
        
            // 从 SDWebImage 获取图片缓存大小
            // key 就是 URL 的完整字符串
            let key = status!.pictureURLs![0].absoluteString
            //提示 ：image未必一定会缓存下来
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            //如果图片不存在的默认大小
            var size = CGSize(width: 150, height: 120)
            
            //判断图像是否存在
            if image != nil {
            
                size = image.size
            }
            
            // 对图像尺寸做进一步判断，防止出现过宽、过窄的情况
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > UIScreen.mainScreen().bounds.width ? 150 : size.width
            
            pictureLayout.itemSize = size
            
            return size
        }
        
        if count == 4 {
            
            let width = itemSize.width * 2 + margin
            
            return CGSize(width: width, height: width)
        }
        
        // 4> 其他
        /**
        2, 3
        5, 6
        7, 8, 9
        */
        // 计算行数

        let row = (count - 1) / rowCount + 1
        let width = itemSize.width * CGFloat(rowCount) + margin * CGFloat(rowCount - 1)
        let height = itemSize.height * CGFloat(row) + margin * CGFloat(row - 1)
        
        return CGSize(width: width, height: height)
    }
    
    //图片布局
    private let pictureLayout = UICollectionViewFlowLayout()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        // 提示：调用父类的构造函数之前，必须给本类的属性初始化
        super.init(frame: frame, collectionViewLayout: pictureLayout)
        
        backgroundColor = UIColor.clearColor()
        
        //注册可重用Cell
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: statusPictureViewCellID)
        
        //设置数据源代理，让自己当自己的数据源，在开发的时候，如果有局部小视图，可以自己充当自己的数据源或代理
        self.dataSource = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

//在swift中，协议同样可以通过 extension 来写，可以将一组协议方法，放置在一起，便于代码维护和阅读
extension StatusPictureView: UICollectionViewDataSource {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return status?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(statusPictureViewCellID, forIndexPath: indexPath) as! StatusPictureViewCell
        
        cell.imageURL = status!.pictureURLs![indexPath.item]
        
        return cell
    }

}

class StatusPictureViewCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
    
        didSet {
        
            iconView.sd_setImageWithURL(imageURL!)
        }
    }

    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI() {
        
        contentView.addSubview(iconView)
        
        iconView.ff_Fill(contentView)
    }
    
    //懒加载
    private lazy var iconView: UIImageView = {
        
        let imageView = UIImageView()
        
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        
        imageView.clipsToBounds = true
        
        return imageView
    }()
}
